package shared.util;

import shared.mess.Content;
import shared.mess.ContentType;
import shared.mess.Message;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author akaovi
 * @createTime 2022/9/16 15:17
 */
public class Util {
    public static final Scanner scan = new Scanner(System.in);

    public static InetAddress getSelfAddress() {
        InetAddress selfIp;
        try {
            selfIp = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            selfIp = null;
        }
        return selfIp;
    }

    public static InetAddress getIpAddress() {
        InetAddress ip;
        try {
            ip = InetAddress.getByName(scan.next());
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return ip;
    }

    public static InetAddress getIpAddress(String s) {
        try {
            return InetAddress.getByName(s);
        } catch (UnknownHostException e) {
            return null;
        }
    }

    public static Message getTextMessage(String message) {
        Content ct = new Content(ContentType.TextType, message.getBytes(StandardCharsets.UTF_8));
        return new Message(getSelfAddress(), ct);
    }

    public static Message getFileMessage(String path) {
        BufferedInputStream bis = null;
        try {
            File sendFile = new File(path);
            FileInputStream fis = new FileInputStream(sendFile);
            bis = new BufferedInputStream(fis);
            Content ct = new Content(ContentType.FileType, bis.readAllBytes(), sendFile.getName());
            return new Message(getSelfAddress(), ct);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new Message(getSelfAddress(), new Content(ContentType.TextType, "文件传送失败".getBytes(StandardCharsets.UTF_8)));
    }

    public static String getStringInput() {
        return scan.next();
    }

    public static boolean isIllegal(String s) {
        switch (s) {
            case "1":
            case "6":
            case "10":
            case "2":
            case "3":
            case "4":
            case "5":
            case "7":
            case "8":
            case "9":
                return true;
            default:
                return false;
        }
    }
}
